package com.tms.security;

import com.tms.domain.Position;
import com.tms.security.entity.Menu;
import com.tms.security.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 确定一个请求需要哪些角色
 *
 * @author ozj
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    /**
     * Ant风格的URL匹配
     */
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    MenuMapper menuMapper;

    /**
     * 取得需要的角色
     *
     * @param object 一个FilterInvocation，从中提取URL
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object)
            throws IllegalArgumentException {
        //取得请求URL
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        String method = ((FilterInvocation) object).getRequest().getMethod();
        //从数据库取得所有的menu
        List<Menu> allMenus = menuMapper.getAllMenus();
        for (Menu menu : allMenus) {
            //如果url匹配则添加相应信息-需要的角色，方法结束
            if (antPathMatcher.match(menu.getPattern(), requestUrl) && menu.getMethod().equalsIgnoreCase(method)) {
                List<Position> positions = menu.getPositions();
                String[] roleArr = new String[positions.size()];
                for (int i = 0; i < roleArr.length; i++) {
                    roleArr[i] = positions.get(i).getName();
                }
                return SecurityConfig.createList(roleArr);
            }
        }
        //如果不存在匹配的url，认为该url登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    /**
     * 用来返回所有定义好的权限资源，Spring Security在启动是会校验相关配置是否正确，
     * 如果不需要校验，直接返回null
     *
     * @return
     */
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    /**
     * 说明该类支持校验
     *
     * @param clazz
     * @return
     */
    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
